<template>
  <!-- 合同初稿 -->
  <CommonTitle
    :titleName="state.type == 1 ? '招标合同协同审批' : '合同初稿'"
  ></CommonTitle>

  <div class="box">
    <el-form
      :inline="true"
      label-width="140"
      :model="formInline"
      :rules="rules"
      ref="formRef"
      class="demo-form-inline"
    >
      <el-row>
        <el-col :span="8" v-if="state.disabled">
          <el-form-item label="审核编号">
            <el-input
              v-model="formInline.flowId"
              disabled
              placeholder=""
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="state.disabled">
          <el-form-item label="审核状态">
            <el-select v-model="formInline.examineStatus" disabled>
              <el-option
                v-for="item in state.auditStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="state.disabled">
          <el-form-item label=" ">
            <el-button
              type="primary"
              @click="openHandler(formInline.routeUrl)"
              class="button_edit"
              >查看流程审批</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="关联项目集">
            <el-input
              v-model="formInline.projectSetName"
              disabled
              placeholder="请输入关联项目集"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目集编号">
            <el-input
              v-model="formInline.projectSetCode"
              disabled
              placeholder="请输入关联项目集"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目立项部门">
            <el-input
              v-model="formInline.departmentName"
              disabled
              placeholder="请输入项目立项部门"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="关联项目">
            <el-input
              v-model="formInline.projectName"
              disabled
              placeholder="请输入关联项目"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目编号">
            <el-input
              v-model="formInline.projectCode"
              disabled
              placeholder="请输入项目编号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目负责人">
            <el-input
              v-model="formInline.responsibleUserName"
              disabled
              placeholder="请输入项目负责人"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="关联任务">
            <el-input
              v-model="formInline.projectTask"
              disabled
              placeholder="请输入关联任务"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="任务编号">
            <el-input
              v-model="formInline.projectTaskId"
              disabled
              placeholder="请输入任务编号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目阶段">
            <el-input
              v-model="formInline.projectStage"
              disabled
              placeholder="请输入项目阶段"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="工作细项名称">
            <el-input v-model="formInline.workName" disabled placeholder="请输入工作细项名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="任务来源">
            <el-input v-model="formInline.taskScore" disabled placeholder="请输入任务来源" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="签订份数" prop="signNumber">
            <el-input
              v-model.number="formInline.signNumber"
              :disabled="state.disabled"
              placeholder="请输入签订份数"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目分类">
            <el-input
              v-model="formInline.projectType"
              disabled
              placeholder="请输入项目分类"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同签约方式">
            <el-select
              :disabled="state.disabled"
              v-model="formInline.signingMethod"
              placeholder="请选择合同签约方式"
            >
              <el-option
                v-for="item in selectionTypeOptions"
                :key="item"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="合同履约期限" prop="serviceStartTime">
            <el-date-picker
              :disabled="state.disabled"
              v-model="formInline.serviceStartTime"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD hh:ss:mm"
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="合同名称" prop="contractName">
            <el-input
              :disabled="state.disabled"
              v-model="formInline.contractName"
              placeholder="请输入合同名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同类型" prop="typeContract">
            <el-select
              :disabled="state.disabled"
              v-model="formInline.typeContract"
              placeholder="请选择合同类型"
            >
              <el-option label="招标合同" :value="1" />
              <el-option label="投资合同" :value="2" />
              <el-option label="建设合同" :value="3" />
              <el-option label="其他合同" :value="4" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同编码" prop="contractNumber">
            <el-input
              :disabled="state.disabled"
              v-model="formInline.contractNumber"
              placeholder="请输入合同编码"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同/协议类别" prop="contractAgreementCategory">
            <el-select
              :disabled="state.disabled"
              v-model="formInline.contractAgreementCategory"
              placeholder="请选择合同/协议类别"
            >
              <el-option v-for="item in typeArr" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同归属部门" prop="responsibleDepartmentId">
            <el-select
              :disabled="state.disabled"
              v-model="formInline.responsibleDepartmentId"
              placeholder="请选择合同归属部门"
            >
              <el-option v-for="item in departmentArr" :label="item.departmentName" :value="item.departmentId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同金额描述" prop="contractAmountDescription">
            <el-input
              :disabled="state.disabled"
              v-model="formInline.contractAmountDescription"
              placeholder="请输入合同金额描述"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="甲方单位" prop="signPartyA">
            <el-input
              :disabled="state.disabled"
              v-model="formInline.signPartyA"
              placeholder="请输入甲方单位"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="乙方单位" prop="signPartyB">
            <el-input
              :disabled="state.disabled"
              v-model="formInline.signPartyB"
              placeholder="请输入乙方单位"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="三方单位" prop="signPartyThree">
            <el-input
              :disabled="state.disabled"
              v-model="formInline.signPartyThree"
              placeholder="请输入三方单位"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同总额" prop="contractAmount">
            <el-input
              :disabled="state.disabled"
              v-model="formInline.contractAmount"
              @input="formInline.contractAmount = limitInputNum(formInline.contractAmount,10,5,true)"
              placeholder="请输入合同总额"
            />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="质保期" prop="warrantyExplain">
            <el-input
              :disabled="state.disabled"
              v-model="formInline.warrantyExplain"
              placeholder="请输入质保期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="state.disabled && state.type == 1">
          <el-form-item label="合同协议编码" prop="contractAgreementCode">
            <el-input
              :disabled="state.disabled"
              v-model="formInline.contractAgreementCode"
              placeholder="请输入合同协议编码"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="state.disabled && state.type == 1">
          <el-form-item label="服务期限" prop="serviceTime">
            <el-input
              :disabled="state.disabled"
              v-model="formInline.serviceTime"
              placeholder="请输入服务期限"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="资金流向">
            <el-select
              :disabled="state.disabled"
              v-model="formInline.capitalFlow"
              placeholder=""
            >
              <el-option label="流入" :value="'1'" />
              <el-option label="流出" :value="'2'" />
            </el-select>
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="8">
          <el-form-item label="合同签订日期" prop="signTime">
            <el-date-picker
              v-model="formInline.signTime"
              type="date"
              :disabled="state.disabled"
              value-format="YYYY-MM-DD HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item label="合同内容" prop="contractContent">
            <el-input
              :disabled="state.disabled"
              v-model="formInline.contractContent"
              type="textarea"
              placeholder="请输入合同内容"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="支付方式" prop="payExplain">
            <el-input
              v-model="formInline.payExplain"
              type="textarea"
              :disabled="state.disabled"
              placeholder="请输入支付方式"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" >
            <el-input
              v-model="formInline.remark"
              :disabled="state.disabled"
              type="textarea"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="合同附件" prop="files">
            <FileMinioUpload
              :restriction="true"
              :disabled="state.disabled"
              :restrictionLimit="9"
              v-model:files="formInline.files"
              :show-button="!state.disabled"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="5" v-if="state.disabled && state.type == 1">
          <el-form-item label="期数">
            <el-input
              :disabled="state.disabled"
              v-model="state.payItem.term"
              placeholder="请输入期数"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5" v-if="state.disabled && state.type == 1">
          <el-form-item label="资金流向">
            <el-select
              :disabled="state.disabled"
              v-model="state.payItem.moneyFlowType"
              placeholder=""
            >
              <el-option label="流入" :value="1" />
              <el-option label="流出" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="7"  v-if="state.disabled && state.type == 1">
          <el-form-item label="付款范围">
            <el-date-picker
              v-model="state.payItem.settlementStartTime"
              type="daterange"
              :disabled="state.disabled"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5"  v-if="state.disabled && state.type == 1">
          <el-form-item label="金额">
            <el-input
              :disabled="state.disabled"
              v-model="state.payItem.payableAmount"
              placeholder="请输入金额"
            />
          </el-form-item>
        </el-col>
        <el-col :span="2" v-if="state.disabled && state.type == 1">
          <el-form-item label="" style="margin-left: 10px;">
            <el-button @click="addRow">添加结算方式</el-button>
          </el-form-item>
        </el-col> -->
        <el-col :span="24" v-if="state.disabled && state.type == 1">
          <el-form-item label="合同结算方式"> </el-form-item>
          <tableCom
            class="table_class"
            :tableHead="tableHead"
            :tableData="tableData"
            :isRadio="false"
            :isIndex="false"
            border
            :height="300"
            :isSelection="false"
          >
            <template #operate>
              <el-table-column label="操作" width="200" align="center" fixed="right" v-if="!state.disabled">
                <template #default="{ row }">
                  <el-button
                    size="small"
                    type="primary"
                    @click="deleteHandler(row)"
                    class="button_delete2"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </template>
          </tableCom>
        </el-col>

        <el-col :span="24" >
          <CommonTitle  titleName="其他信息"></CommonTitle>
        </el-col>
        <el-col :span="8" >
          <el-form-item label="申请人">
            <el-input disabled v-model="formInline.applyUserName" placeholder="请输入申请人" />
          </el-form-item>
        </el-col>

        <el-col :span="8" >
          <el-form-item label="申请部门">
            <el-input
              disabled
              v-model="formInline.applyDepartmentName"
              placeholder="请输入申请部门"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" >
          <el-form-item label="创建时间">
            <el-input
              disabled
              v-model="formInline.createTime"
              placeholder="请输入创建时间"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="24" v-if="state.disabled">
          <el-form-item label="查看审批流程">
            <el-button type="primary" @click="openHandler(formInline.routeUrl)">查看审批流程</el-button>
          </el-form-item>
        </el-col> -->
      </el-row>
    </el-form>

    <span class="dialog-footer" v-if="!state.disabled">
      <el-button @click="submit" class="button_view">发起审批</el-button>
      <el-button type="primary" @click="goback" class="button_cancel2"> 取消 </el-button>
    </span>
  </div>
</template>

<script setup>
import { contractApi, department } from '@/api/project'

import {ref, reactive, onBeforeMount, onMounted, watch, nextTick} from 'vue'
import {
  ElDialog,
  ElMessage,
  ElDatePicker,
  ElSelect,
  ElOption,
  ElRow,
  ElCol,
  ElForm
} from 'element-plus'
import CommonTitle from '@/components/CommonTitle.vue'
import TableCom from '@/components/table/table.vue'
import { useRouter, useRoute } from 'vue-router'
import FileMinioUpload from "@/components/FileMinioUpload.vue";
import {
  getURLhandler,
  nanoid
} from '@/views/constructionProjectManage/static/utools.js'
import {limitInputNum} from "@/common/utils/GlobalUtils";
import {selectionTypeOptions} from "@/common/dict/dictCollect";
import {useSetFormData} from "@/hooks/setFormData";

let router = useRouter()
let route = useRoute()
const state = reactive({
  auditStatus: [
    {
      label: '待审核',
      value: '1'
    },
    {
      label: '审核成功',
      value: '2'
    },
    {
      label: '审核驳回',
      value: '3'
    }
  ],
  user: '',
  projectTaskId: '',
  projectId: '',
  itemId: '',
  type: '',
  // payItem: {
  //   term: '',
  //   // moneyFlowType: 1,
  //   settlementStartTime: [],
  //   payId: nanoid()
  // },
  disabled: false
})
const formInline = reactive({
  examineStatus:'1',
})

const {
    setData,
    getData,
    getAttributeNum,
    filterEmptyAttributes,
} = useSetFormData({
    key:`contract-${getURLhandler(route.path).projectId}-${getURLhandler(route.path).projectTaskId}-${getURLhandler(route.path).itemId}-type${getURLhandler(route.path).type}`,
});


const rules = {
    signNumber: [
    { required: true, message: '签订份数不能为空', trigger: 'blur' }
  ],
    contractName: [
    { required: true, message: '合同名称不能为空', trigger: 'blur' }
  ],
  typeContract: [
    { required: true, message: '合同类型不能为空', trigger: 'blur' }
  ],
  contractNumber: [
    { required: true, message: '合同编号不能为空', trigger: 'blur' }
  ],
  signPartyA: [
    { required: true, message: '签约甲方不能为空', trigger: 'blur' }
  ],
  signPartyB: [
    { required: true, message: '签约乙方不能为空', trigger: 'blur' }
  ],

  contractAmount: [
    { required: true, message: '合同金额不能为空', trigger: 'blur' }
  ],

  // serviceStartTime: [
  //   { required: true, message: '服务期限不能为空', trigger: 'blur' }
  // ],
  signTime: [
    { required: true, message: '合同签订日期不能为空', trigger: 'blur' }
  ],
  contractContent: [
    { required: true, message: '合同内容不能为空', trigger: 'blur' }
  ],
  payExplain: [
    { required: true, message: '支付方式不能为空', trigger: 'blur' }
  ],
  remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
  files: [{ required: true, message: '附件不能为空', trigger: 'blur' }],
  contractAmountDescription: [
    { required: true, message: '合同金额描述不能为空', trigger: 'blur'}
  ],
  contractAgreementCategory: [
    { required: true, message: '请选择合同/协议类别', trigger: 'blur'}
  ],
  responsibleDepartmentId: [
    { required: true, message: '请选择合同归属部门', trigger: 'blur'}
  ],
}
// 1, "公开招标
// 2, "公开竞争性谈判
// 3, "公开竞争性磋商
// 4, "择优比选"
// 5, "单一来源采购
// 6, "邀请竞争性谈判
// 7, "邀请竞争性磋商
// 8, "择优询价"
// 9, "单一来源采购
const projectTendersWayList = reactive([
  {
    label: '公开招标',
    value: '1'
  },
  {
    label: '公开竞争性谈判',
    value: '2'
  },
  {
    label: '公开竞争性磋商',
    value: '3'
  },
  {
    label: '择优比选',
    value: '4'
  },
  {
    label: '单一来源采购',
    value: '5'
  },
  {
    label: '邀请竞争性谈判',
    value: '6'
  },
  {
    label: '邀请竞争性磋商',
    value: '7'
  },
  {
    label: '择优询价',
    value: '8'
  },
  {
    label: '单一来源采购',
    value: '9'
  }
])

const typeArr = [
  {
    label: '修缮改造类（非工程建设）',
    value: 1
  },
  {
    label: '物资采购类（非工程建设）',
    value: 2
  },
  {
    label: '物业服务类（非工程建设）',
    value: 3
  },
  {
    label: '其他服务类（非工程建设）',
    value: 4
  },
  {
    label: '设施设备系统维保及维修类（非工程建设）',
    value: 5
  },
  {
    label: '施工类（工程建设）',
    value: 6
  },
  {
    label: '与工程建设有关的重要设备、材料等货物采购类（工程建设）',
    value: 7
  },
  {
    label: '勘察、设计、监理服务类（工程建设）',
    value: 8
  },
  {
    label: '检查、检测、咨询、测绘、图审等其他工程服务类（工程建设）',
    value: 9
  },
  {
    label: '资产租售类',
    value: 10
  },
  {
    label: '办公物资类',
    value: 11
  },
];
const tableData = ref([]);
// term: '',
//     moneyFlowType: 0,
//     settlementStartTime: [],
//     payId: nanoid()
const tableHead = ref([
  {
    prop: 'term',
    label: '期数'
  },
  {
    prop: 'settlementStartTime',
    label: '付款范围',
    formatter: (row) => {
      return row.settlementStartTime.join('-')
    }
  },
  {
    prop: 'payableAmount',
    label: '金额'
  }
])
const handel = () => {}
const deleteHandler = (row) => {
  tableData.value = tableData.value.filter((item) => item.payId !== row.payId)
}
const addRow = () => {
  state.payItem.payId = nanoid()
  tableData.value.push(JSON.parse(JSON.stringify(state.payItem)))
}
const goback = () => {
  router.go(-1)
}
const formRef = ref(null)
const submit = () => {
  formRef.value.validate(async (valid, fields) => {
    if (valid) {
      formInline.projectId = state.projectId
      formInline.tenderTaskId = state.projectTaskId
      // if(tableData.value.length==0){
      //   ElMessage.error('请添加合同结算方式')
      //   return
      // }
      let obj = JSON.parse(JSON.stringify(formInline))
      // obj.serviceStartTime = formInline.serviceStartTime[0];
      // obj.serviceEndTime = formInline.serviceStartTime[1];
      obj.itemId = state.itemId
      obj.type = state.type
      // obj.payList = []
      // tableData.value.forEach((item) => {
      //   obj.payList.push({
      //     term: item.term,
      //     // moneyFlowType: item.moneyFlowType,
      //     settlementStartTime: item.settlementStartTime[0] + ' 00:00:00',
      //     settlementEndTime: item.settlementStartTime[1] + ' 00:00:00',
      //     payableAmount: item.payableAmount
      //   })
      // })
      await contractApi.contractAdd(obj).then((res) => {
        if (res.code === '200') {
          ElMessage.success('操作成功')
          router.go(-1)
        }
      })
    }
  })
}
onBeforeMount(() => {
  state.projectTaskId = getURLhandler(route.path).projectTaskId
  state.projectId = getURLhandler(route.path).projectId
  state.type = getURLhandler(route.path).type
  state.itemId = getURLhandler(route.path).itemId
  state.disabled = +getURLhandler(route.path).isLook
})
const openHandler=(url)=>{
  window.open(url)
}

// 获取合同归属部门选项
let departmentArr = ref([]);
let getAllDepartments = async() => {
  let { data } = await department.getAllDepartments();
  departmentArr.value = data
}

const isBool = ref(false);
watch([()=>state.disabled,()=>formInline],(newVal)=>{
    if(newVal[0]===0 &&  Object.keys(newVal[1]).length > 3 && isBool.value){
        setData(formInline);
    }
},{deep:true})

const getProjectData = () => {
    contractApi
        .contractLook({
            taskId: state.projectTaskId,
            itemId: state.itemId,
            type: state.type,
            projectId: state.projectId
        })
        .then(async (res) => {
            if (res.code === '200') {
                let obj = {};
                if (getAttributeNum(await getData()) > getAttributeNum(res.data)) { // 缓存中的数据比接口数据的多
                    obj = Object.assign({},await getData(), filterEmptyAttributes(res.data))
                }
                if (getAttributeNum(await getData()) <= getAttributeNum(res.data)) { // 缓存中的数据比接口数据的少或者相同
                    obj = filterEmptyAttributes(res.data)
                }


                for (const key in obj) {
                    if (key === 'files' || key === 'fileList') {
                        formInline['files'] = obj[key] || []
                        continue
                    }
                    if (key === 'payList') {
                        if (obj[key] && obj[key].length > 0) {
                            obj[key].forEach((item) => {
                                item.settlementStartTime = [
                                    item.settlementStartTime,
                                    item.settlementEndTime
                                ]
                            })
                            tableData.value = obj[key]
                        } else {
                            tableData.value = []
                        }
                        continue
                    }
                    formInline[key] = obj[key]
                }

                await nextTick(() => {
                    isBool.value = true;
                })
            }
        });
}

onMounted(() => {
  getProjectData();
  getAllDepartments();
})
</script>

<style lang="scss" scoped>
.el-form-item,
.el-select {
  width: 100%;
}
.box {
  border-radius: 10px;
  border: 1px solid #e3e7f1;
  padding: 34px 90px;
}
.table_class {
  margin-top: 20px;
  margin-bottom: 20px;
}
:deep(.el-input__wrapper) {
  width: 100%;
  height: 40px;
}
:deep(.el-date-editor) {
  width: 100%;
  height: 40px;
}
</style>
